package org.jim.server.command.cs;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.exception.ImException;
import org.jim.core.helper.cs.ICsSessionHelper;
import org.jim.core.packets.pub.consts.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.cs.session.command.GetCsSessionReqCmd;
import org.jim.core.packets.cs.session.command.GetCsSessionRespCmd;
import org.jim.core.packets.cs.session.vo.JimCsGetSessionReq;
import org.jim.core.packets.cs.session.vo.JimCsGetSessionResp;
import org.jim.core.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.command.CommandHandler;
import org.jim.server.protocol.ProtocolManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 版本: [1.0]
 * 功能说明 会话cmd消息命令处理器,创建或者检查session
 */
@CommandHandler(cmd = Command.COMMAND_GET_SESSION_REQ)
@Slf4j
public class CsGetSessionReqHandler extends AbstractCmdHandler {
    @Autowired
    private ICsSessionHelper csSessionHelper;



    @Override
    public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException {
        if (packet.getBody() == null) {
            return ProtocolManager.Converter.respPacket(new RespBody(Command.COMMAND_SESSION_RESP, ImStatus.C10032), channelContext);
        }
        //请求中构建出请求对象
        GetCsSessionReqCmd sessionReqCmd = JsonKit.toBean(packet.getBody(), GetCsSessionReqCmd.class);
        //当前登录用户
        String userId = channelContext.getUserId();//登录用户
        Assert.notBlank(userId);
        JimCsGetSessionReq req = new JimCsGetSessionReq();
        req.setUid(userId);
        req.setPageNum(sessionReqCmd.getPageNum());
        req.setPageSize(sessionReqCmd.getPageSize());
        req.setSort(sessionReqCmd.getSort());
        req.setOperateType(sessionReqCmd.getOperateType());
        //查询会话列表
        List<JimCsGetSessionResp> respList = csSessionHelper.getList(req);
        return ProtocolManager.Converter.respPacket(new GetCsSessionRespCmd().setSessionList(respList).setCode(ImStatus.C_OK.getCode()), channelContext);
    }

    @Override
    public Command command() {
        return Command.COMMAND_GET_SESSION_REQ;
    }
}
